﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.IO;
using System.Xml;
using System.Security.Policy;
using System.Web.Script.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
//using log4net;
using System.Reflection;
using System.Web;
using System.Diagnostics;
//using OAUS.Core;

namespace WXServer
{
    public class HttpTool
    {
        JavaScriptSerializer serializer = new JavaScriptSerializer();
        /// <summary>
        /// 日志工具
        /// </summary>
        //static ILog log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
        /// <summary>
        /// 获取文本数据
        /// </summary>
        /// <param name="dict">数据字典</param>
        /// <returns>文本数据拼接字符串</returns>
        public static string GetTextMoths(Dictionary<string, object> dict, bool jiami)
        {
            string strURL = "";
            if (jiami)
            {
                //if (!dict.ContainsKey("RequstType"))
                //    dict.Add("RequstType", 0);
                strURL += Convert.ToBase64String(Obj2Byte(dict)).Replace("+", "%2B");
            }
            else
            {
                foreach (string key in dict.Keys)
                {
                    if (dict[key].GetType().FullName.Contains("System.Collections.Generic.Dictionary") || dict[key].GetType().FullName.Contains("System.Collections.Generic.List`1"))
                    //if (dict[key].GetType().FullName == "System.String")
                    {
                        strURL += key + "=" + Convert.ToBase64String(Obj2Byte(dict[key])).Replace("+", "%2B") + "&";
                    }
                    else if (dict[key].GetType().FullName.Contains("System.IO.FileStream"))
                    {
                        FileStream fs = dict[key] as FileStream;
                        byte[] buffer = new byte[fs.Length];
                        fs.Read(buffer, 0, buffer.Length);
                        strURL += key + "=" + Convert.ToBase64String(buffer).Replace("+", "%2B") + "&";
                        strURL += "filename" + "=" + fs.Name + "&";
                    }
                    else
                    {
                        strURL += key + "=" + dict[key].ToString() + "&";
                    }
                }
                try
                {
                    //strURL += "dwVersion=" + VersionHelper.GetCurrentVersion().ToString();
                }
                catch (Exception ex)
                {
                }
            }
            return strURL;
        }
        /// <summary>
        /// 获取文件数据
        /// </summary>
        /// <param name="dict">数据字典</param>
        /// <returns>文件数据拼接字符串</returns>
        public static FileStream GetFileMoths(Dictionary<string, object> dict)
        {
            string strURL = "";
            foreach (string key in dict.Keys)
            {
                if (dict[key].GetType().FullName.Contains("System.IO.FileStream"))
                {
                    // 文件参数头  
                    //const string filePartHeader =
                    //    "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\n" +
                    //     "Content-Type: application/octet-stream\r\n\r\n";
                    //string fileHeader = string.Format(filePartHeader, "file", fileName);
                    //byte[] fileHeaderBytes = Encoding.UTF8.GetBytes(fileHeader);

                    return (dict[key] as FileStream);
                }
            }
            return null;
        }
        private static byte[] Obj2Byte(object obj)
        {
            if (obj == null)
                obj = "";
            if (obj.GetType().FullName == "System.String")
            {
                return Encoding.UTF8.GetBytes((string)obj);
            }
            MemoryStream ms = new MemoryStream();
            BinaryFormatter formatter = new BinaryFormatter();
            formatter.Serialize(ms, obj);
            return ms.ToArray();
        }


        public static string PostMoths(string Url, Dictionary<string, object> dict)
        {
            string strURL = "";
            foreach (string key in dict.Keys)
            {
                strURL += key + "=" + dict[key].ToString() + "&";
            }
            return strURL;
        }
        /// <summary>
        /// 将json数据反序列化为Dictionary
        /// </summary>
        /// <param name="jsonData">json数据</param>
        /// <returns></returns>
        public static Dictionary<string, object> JsonToDictionary(string jsonData)
        {
            //实例化JavaScriptSerializer类的新实例
            JavaScriptSerializer jss = new JavaScriptSerializer();
            jss.MaxJsonLength = Int32.MaxValue;
            try
            {
                //将指定的 JSON 字符串转换为 Dictionary<string, object> 类型的对象
                return jss.Deserialize<Dictionary<string, object>>(jsonData);
            }
            catch (Exception ex)
            {
                //log.DebugFormat("\r\n错误描述：json转换成字典失败。\r\nInData:【{0}】\r\nOutData:【{1}】", jsonData, ex.Message); 
                throw new Exception(ex.Message);
            }
        }

        public static T DictToObject<T>(object obj)
        {
            JavaScriptSerializer jss = new JavaScriptSerializer();
            jss.MaxJsonLength = Int32.MaxValue;
            string resultstr = jss.Serialize(obj);
            T info = jss.Deserialize<T>(resultstr);
            return info;
        }

        public static string Get(string Url, Dictionary<string, object> dict)
        {
            try
            {
                string param = GetTextMoths(dict, false);
                byte[] bs = Encoding.ASCII.GetBytes(param);
                //System.Net.HttpWebRequest request;
                //// 创建一个HTTP请求  
                //request = (System.Net.HttpWebRequest)WebRequest.Create(strURL);
                HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(Url);
                request.Method = "Get";
                System.Net.HttpWebResponse response;
                response = (System.Net.HttpWebResponse)request.GetResponse();
                System.IO.StreamReader myreader = new System.IO.StreamReader(response.GetResponseStream(), Encoding.UTF8);
                string responseText = myreader.ReadToEnd();
                myreader.Close();
                return responseText;
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }
        public static Dictionary<string, object> SendText(string Url, string param)
        {  // 读取文本字节
            byte[] txtBs = Encoding.UTF8.GetBytes(param);

            // 开始拼数据  
            MemoryStream memStream = new MemoryStream();

            // 拼接文本数据
            memStream.Write(txtBs, 0, txtBs.Length);

            memStream.Position = 0;
            byte[] tempBuffer = new byte[memStream.Length];
            memStream.Read(tempBuffer, 0, tempBuffer.Length);
            memStream.Close();

            //System.GC.Collect();
            //System.Net.ServicePointManager.DefaultConnectionLimit = 200; 
            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(Url);
            //request.Timeout = 5 * 60 * 1000; // 5 minutes  
            //request.KeepAlive = false;
            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded";
            request.ContentLength = tempBuffer.Length;
            //request.SendChunked = true;
            using (Stream reqStream = request.GetRequestStream())
            {
                reqStream.Write(tempBuffer, 0, tempBuffer.Length);
                reqStream.Close();
            }
            //HttpWebResponse wr;
            //try
            //{
            //    wr = (HttpWebResponse)request.GetResponse();
            //}
            //catch (WebException ex)
            //{
            //    wr = (HttpWebResponse)ex.Response;
            //}
            //StreamReader sr = new StreamReader(wr.GetResponseStream());
            //string strHtml = sr.ReadToEnd();
            using (WebResponse wr = request.GetResponse())
            {
                System.IO.StreamReader myreader = new System.IO.StreamReader(wr.GetResponseStream(), Encoding.UTF8);
                string responseText = myreader.ReadToEnd();
                myreader.Close();
                Dictionary<string, object> json = JsonToDictionary(responseText);
                return json;
            }
        }

        private static void RespCallBack(IAsyncResult asynchronousResult)
        {
            RequestState requestState = (RequestState)asynchronousResult.AsyncState;
            HttpWebRequest request = requestState.request;
            Dictionary<string, object> json = new Dictionary<string, object>();
            if (asynchronousResult.IsCompleted)
            {
                using (WebResponse wr = request.GetResponse())
                {
                    System.IO.StreamReader myreader = new System.IO.StreamReader(wr.GetResponseStream(), Encoding.UTF8);

                    string responseText = myreader.ReadToEnd();
                    myreader.Close();

                    byte[] fileBs = Encoding.UTF8.GetBytes(responseText);
                }
            }
        }
    }
    public class RequestState
    {
        public HttpWebRequest request;
    }
}
